'use strict'

const webSocket = require('nodejs-websocket');

class Ws {
    /**
     * 初始化ws相关条件
     */
    constructor() {
        this.deviceList = new Map();
        this.server = webSocket.createServer((conn) => {
            console.log(`${conn.headers.origin}连接客户端连接成功！`)
            conn.on('text', (msg) => {
                let data = JSON.parse(msg);

                if (data.cmd === 'heart') {
                    console.log('heart');
                    let hearNews = JSON.stringify({
                        cmd: 'heart',
                        content: {
                            "desc": "服务端在线!"
                        }
                    })
                    conn.sendText(hearNews);
                } else if (data.cmd === 'port') {
                    const port = data.content.devicePort
                    this.deviceList.set(port, conn.key)
                    let backNews = JSON.stringify({
                        cmd: 'reply',
                        content: {
                            desc: "收到port端口信息!"
                        }
                    })
                    conn.sendText(backNews);
                } else {
                    let backNews = JSON.stringify({
                        cmd: 'reply',
                        content: {
                            desc: "请发送正确的数据格式!"
                        }
                    })
                    conn.sendText(backNews);
                }
            })

            conn.on('close', () => {
                console.log('连接关闭');
            })

            conn.on('error', (code, reason) => {
                console.log(`ws连接发生错误:${code},${reason}`);
            })

        }).listen(4000, '127.0.0.1',
            () => console.log(`ws服务启动`))
    }
    /**
     * 向目标目检工位发送缓存数据
     * @param {Number} port plc的哪个端口传过来的数据
     * @param {JSON} msg 命中的缓存数据
     */
    sendPanelInfo(port, msg) {
        console.log(this.deviceList);
        let deviceKey = null;
        // 找到port对应的连接的key
        for (const device of this.deviceList) {
            if (device[0] == port) {
                deviceKey = device[1];
            }
        }
        // 发送到指定的目检浏览器
        this.server.connections.forEach((conn) => {
            console.log(conn.key);
            if (deviceKey == conn.key) {
                let data = JSON.stringify({
                    cmd: 'reply',
                    content: {
                        desc: "缺陷数据!",
                        station: true,
                        msg
                    }
                })
                conn.sendText(data);
                console.log(`已发送目检信息给前端！`);
            }
        })
    }

    static getInstance() {
        if (Ws.instance) {
            return Ws.instance;
        } else {
            Ws.instance = new Ws();
            return Ws.instance;
        }
    }
}

module.exports = Ws;